package com.baizhi.controller;

import com.baizhi.entity.Book;
import com.baizhi.entity.Category;
import com.baizhi.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("Book")
public class BookController {
    @Autowired
    private BooksService booksService;
    @RequestMapping("AllBook")
    public String AllBook(HttpServletRequest req, Integer pageNo){
        //每页显示的条数
        Integer pageCount=3;
        int pageIndex = 1;
        if (pageNo!=null){
            pageIndex=pageNo;
        }
        //调用业务层方法
        List<Category> categories = booksService.selectCategorysByPage(pageIndex,pageCount);
        //计算总数的
        int totalCount = booksService.selectToalCount();

        int totalPage = totalCount%pageCount==0?totalCount/pageCount:totalCount/pageCount+1;
        //将数据保存到作用域里
        req.setAttribute("categories",categories);
        //将pageNo存放在req作用域里
        req.setAttribute("pageNo",pageIndex);
        //将总条数存放在req作用域里
        req.setAttribute("totalPage",totalPage);

        return "booklist";
    }
    @RequestMapping("updateBook")
    public String updateBook(Book book){
        //调用业务层方法
        int updatebook = booksService.updatebook(book);
        if (updatebook==1){
            System.out.println("修改成功");
            return "forward:/Book/AllBook.do";
        }else{
            System.out.println("修改失败");
            return "forward:/Book/AllBook.do";
        }
    }
    @RequestMapping("deteleBook")
    public String deleteBook(Integer id){
        //调用业务层方法
        int deletebook = booksService.deletebook(id);
        if (deletebook==1){
            System.out.println("删除成功");
            return "forward:/Book/AllBook.do";
        }else{
            System.out.println("登录失败");
            return "forward:/Book/AllBook.do";
        }
    }
    @RequestMapping("detelesBook")
    public String deletesBook(String[] ids){
        List<Integer> list = new ArrayList<Integer>();
        for (String i:ids) {
            int i1=Integer.parseInt(i);
            list.add(i1);
        }
        //调用业务层方法
        int deletesbook = booksService.deletesbook(list);
        if (deletesbook==1){
            System.out.println("删除成功");
            return "forward:/Book/AllBook.do";
        }else{
            System.out.println("登录失败");
            return "forward:/Book/AllBook.do";
        }
    }
    @RequestMapping("addBook")
    public String addBook(Book book){
        //调用业务层方法
        int insertbook = booksService.insertbook(book);
        if (insertbook==1){
            System.out.println("增加成功");
            return "forward:/Book/AllBook.do";
        }else{
            System.out.println("增加失败");
            return "forward:/Book/AllBook.do";
        }
    }
}
